'use strict';

stareal
    .controller("ActivityDetailController", function ($scope, $stateParams, $api, $state, $alert, localStorageService,$interval,$window,$sce,$lazyLoader) {
        $scope.id = $stateParams.id;
        if($stateParams.app==1){
            $scope.BackStatus=true;
            //$("#loadingGif").css("display",'none');
            $scope.dowload_appStatus=true;
        }
        //$scope.dowload_appStatus=true;
        $scope.user=localStorageService.get('user');
        $scope.sort=2;  // 1热门   2时间
        $scope.text="";
        $scope.CUrIndex=localStorageService.get('activeclassifyInde');
        $scope.CUrType=localStorageService.get('activeclassifyType');
        $scope.sharUrl='https://test.djx.m.opentickets.cn/?&#/'; // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致'
        //获取详情
        var timer=null;
        //分享
        //微信分享http://192.168.1.4:9090/oauth/getSignature
        //活动新接口  app/activity/activityFindOtherById    老  app/view/activityfind
        $api.get("app/activity/activityFindOtherById", {id: $stateParams.id}, true)
            .then(function (ret) {
                var activitysdetail = ret.data;
                // console.log(activitysdetail);activity_type // 1 抽奖   2抢楼   3 写观演记
                activitysdetail.content= $sce.trustAsHtml(activitysdetail.content);
                var time=activitysdetail.enddate;
                var time0=activitysdetail.startdate;
                $scope.end_time = Date.parse(new Date(time))//兼容ios问题
                $scope.start_time=Date.parse(new Date(time0))//兼容ios问题
                var starteTime= $scope.start_time//开始
                var expiredTime =  $scope.end_time;//过期时间戳
                var nowDate =  Date.parse(new Date());//现在时间戳
                $scope.date0=starteTime-nowDate;//是否开始
                $scope.date = expiredTime-nowDate; //是否结束
                timer = $interval(updateTime,1000)
                updateTime()
                function updateTime() {
                    $scope.date -= 1000;
                    if($scope.date0>=0){
                        activitysdetail.state='未开始';
                    }else if($scope.date0<0&&$scope.date>0){
                        activitysdetail.state='开始';
                    } else if($scope.date<=0){
                        activitysdetail.state='已结束';
                        $interval.cancel(timer);
                    }
                }
                if(activitysdetail.count>activitysdetail.numbers){
                    activitysdetail.bar=parseInt(100/100*100);
                    activitysdetail.barshu=parseInt(activitysdetail.count/activitysdetail.numbers*100)+'%';
                }else{
                    activitysdetail.bar=parseInt(activitysdetail.count/activitysdetail.numbers*100);
                    activitysdetail.barshu=parseInt(activitysdetail.count/activitysdetail.numbers*100)+'%';
                }
                $scope.activitysdetail = activitysdetail;
                // video.content = JSON.parse(sContent.content);//转化成对象
                // $scope.sContent = sContent;
                var h=$(window).height()-1.4*parseFloat(document.documentElement.style.fontSize)+"px";
                $("#wrapper_container").height(h);
                $scope.getShare();
            },function(err){
                $alert.show(err);
            })
        $scope.getShare=function(){
            $api.get("app/share/getSignature", {url: window.location.href.split('#')[0]})
                .then(function (ret) {
                    if (ret) {
                        var data = ret.data;
                        wx.config({
                            debug: false,
                            appId: data.appid,
                            timestamp: data.timestamp,
                            nonceStr: data.nonceStr,
                            signature: data.signature,
                            jsApiList: [
                                'onMenuShareTimeline',
                                'onMenuShareAppMessage',
                                'onMenuShareQQ',
                                // 'onMenuShareWeibo',
                                'onMenuShareQZone'
                            ]
                        });
                        wx.ready(function () {
                            //分享到朋友圈
                            wx.onMenuShareTimeline({
                                title: $scope.activitysdetail.title, // 分享标题
                                desc: '我在独角秀分享了一个不错的活动！', // 分享描述
                                link: $scope.sharUrl+'main/activedetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.activitysdetail.thumb, // 分享图标
                                success: function () {
                                    // 用户确认分享后执行的回调函数
                                    //alert('你好');
                                    $alert.show("分享成功");
                                },
                                cancel: function () {
                                    // 用户取消分享后执行的回调函数
                                    // alert('你好....');
                                }
                            });
                            //分享给朋友
                            wx.onMenuShareAppMessage({
                                title: $scope.activitysdetail.title, // 分享标题
                                desc: '我在独角秀分享了一个不错的活动！', // 分享描述
                                link: $scope.sharUrl+'main/activedetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.activitysdetail.thumb, // 分享图标
                                type: 'link', // 分享类型,music、video或link，不填默认为link
                                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                success: function () {
// 用户确认分享后执行的回调函数
                                    $alert.show("分享成功");
                                    // alert('你好....');
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                            wx.onMenuShareQQ({
                                title: $scope.activitysdetail.title, // 分享标题
                                desc: '我在独角秀分享了一个不错的活动！', // 分享描述
                                link: $scope.sharUrl+'main/activedetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.activitysdetail.thumb, // 分享图标
                                success: function () {
// 用户确认分享后执行的回调函数
                                    $alert.show("分享成功");
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                            wx.onMenuShareQZone({
                                title: $scope.activitysdetail.title, // 分享标题
                                desc: '我在独角秀分享了一个不错的活动！', // 分享描述
                                link: $scope.sharUrl+'main/activedetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl:$scope.activitysdetail.thumb, // 分享图标
                                success: function () {
// 用户确认分享后执行的回调函数
                                    $alert.show("分享成功");
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                        });
                        wx.error(function (res) {
                            //console.log(res);
                            //alert("微信分享接口配置失败");
                        });
                    }
                })
        }
        var refresh=function(sort){
            $scope.goods = new $lazyLoader("app/viewcomment/goodComments", {
                good_id:$stateParams.id,
                type:7,
                sort:sort
            },true);
            $scope.goods.nextPage();
        }
        refresh(2);
        //切换
        $scope.switchComent=function(index){
            $scope.sort=index;
            refresh(index);
        }
        $scope.gotoViewEdit=function(){
            var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    localStorageService.set('token', '');
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs)+"&connect_redirect=1#wechat_redirect";
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            $state.go('main.viewwangeditor',{id:'',viewshowname:''},true);
        }
        $scope.goToJoin=function(){  //加入抽奖
            var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    localStorageService.set('token', '');
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state=" + encodeURIComponent(rs)+"&connect_redirect=1#wechat_redirect";

                } else {
                    location.href = "#/main/login/" + encodeURIComponent(rs);
                }
                return false;
            }

            // $alert.show('请点击屏幕上方下载独角秀App,加入抽奖活动!');
            $scope.encryptkey=$("#encryptkey").val();
            $scope.encryptiv=$("#encryptiv").val();
            $scope.mobile_ip=returnCitySN["cip"];
            var stardate=new Date().getTime().toString()+'paomi';
            var data = $scope.mobile_ip+'paomi'; //mobile_ip;
            var key = CryptoJS.enc.Latin1.parse($scope.encryptkey);
            var iv = CryptoJS.enc.Latin1.parse($scope.encryptiv);
            var encrypted = CryptoJS.AES.encrypt(data, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.ZeroPadding
            });
            var encrypteddate = CryptoJS.AES.encrypt(stardate, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.ZeroPadding
            });
            var encryptedmobileType = CryptoJS.AES.encrypt('H5paomi',key,{
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.ZeroPadding
            });
            $scope.mobile_ip=encrypted.toString();
            $scope.encryptedmobileType=encryptedmobileType.toString();
            $scope.encrypteddate=encrypteddate.toString();
            // $alert.show('请点击屏幕上方下载独角秀App,加入应援!');
            $api.post('app/activity/lotteryActivityH5', {id: $stateParams.id,mobileType:$scope.encryptedmobileType,mobile_ip:$scope.mobile_ip,encrypt:$scope.encrypteddate}, true)
                .then(function (ret) {
                    if(ret.follow==1){
                        if(_czc!=undefined&&_czc!=null&&_czc!=''){
                            _czc.push(["_trackEvent", 'h5-抽奖活动参与', '参与成功', '参与量', 'activity']);
                        }
                        $scope.activitysdetail.likes=1;
                        $scope.activitysdetail.count++;
                        if(  $scope.activitysdetail.count>  $scope.activitysdetail.numbers){
                            $scope.activitysdetail.bar=parseInt(100/100*100);
                            $scope.activitysdetail.barshu=parseInt(activitysdetail.count/activitysdetail.numbers*100)+'%';
                        }else{
                            $scope.activitysdetail.bar=parseInt(  $scope.activitysdetail.count/  $scope.activitysdetail.numbers*100);
                            $scope.activitysdetail.barshu=parseInt(  $scope.activitysdetail.count/  $scope.activitysdetail.numbers*100)+'%';
                        }
                    }
                },function(err){
                    $alert.show(err);
                })
        }
        $scope.closedDowload=function(){
            $scope.dowload_appStatus=false;
        }
        //收藏
        $scope.viewCollection=function() {
            var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    localStorageService.set('token', '');
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state=" + encodeURIComponent(rs)+"&connect_redirect=1#wechat_redirect";
                } else {
                    location.href = "#/main/login/" + encodeURIComponent(rs);
                }
                return false;
            }

            $api.post("app/view/collection", {viewid: $stateParams.id,type:7}, true)
                .then(function (ret) {
                    if (ret.follow == 1) {
                        $alert.show('收藏成功！')
                        $scope.activitysdetail.favor=1;
                    }else{
                        $alert.show('取消收藏！');
                        $scope.activitysdetail.favor=0;
                    }

                },function(err){
                    $alert.show(err);
                })

        }
        //点赞
        $scope.IsPraiseView = function (commentid,Index,num,from,event){  //tiao
            var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    localStorageService.set('token', '');
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs)+"&connect_redirect=1#wechat_redirect";
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            event.stopPropagation()//阻止冒泡
            $api.post("app/viewcomment/praise", {comment_id:commentid,type:7}, true)
                .then(function (ret) {
                    if(from=='detail'){//详情页
                        $scope.goods.items[Index].is_praise = ! $scope.goods.items[Index].is_praise;
                        $scope.goods.items[Index].like = parseInt(ret.praise)+num;
                    }
                },function (err) {
                    $alert.show(err)
                })
        }
        //弹出编辑框
        $scope.tanViewCommen=function(){
            var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    localStorageService.set('token', '');
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                // $state.go("main.login",{})
                // return false;
                var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {//判断是否是微信浏览器
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state=" + encodeURIComponent(rs)+"&connect_redirect=1#wechat_redirect";
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }

                return false;
            }
            $("#viewComments_send").show();
            $('#viewComments_send').css('-webkit-overflow-scroll','touch');
        }
        //取消观演记编辑
        $scope.cancelviewCommment=function(){
            $("#editComment").val("");
            $scope.text='';
            $("#viewComments_send").hide();
            $('#viewComments_send').css('-webkit-overflow-scroll','auto');
        }
        $('textarea').on('click', function () {
            var target=this;
            setTimeout(function(){
                document.body.scrollTop = document.body.scrollHeight;
            },300);
        });
        $scope.LeftLength=function () {
            if($scope.text!=''&&$scope.text!=null&&$scope.text!=undefined){
                if($scope.text.length>150){
                    var value = $scope.text.substring(0, 150);
                    $scope.text= value;
                }
                return $scope.text.length;
            }else{
                return 0;
            }
        }
        //确定发表
        $scope.sendviewCommment=function(){
            if($("#editComment").val()==''){
                $alert.show("请填写发表的内容！");
                return false;
            }
            if($("#editComment").val().length<=3){
                $alert.show("评论内容请多于3个字！");
                return false;
            }
            $("#viewComments_send").hide();
            $api.post("app/viewcomment/create",{
                good_id:$stateParams.id,
                content:$("#editComment").val(),
                type:7
            },true).then(function (ret) {
                $alert.show("发表成功！");
                refresh(2);
            },function(err){
                $alert.show(err);
                $("#editComment").val('');
            })

        }
        //举报 操作
        $scope.showoperationdailog=function(ID,useID,detail){
            var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    localStorageService.set('token', '');
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.activedetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs)+"&connect_redirect=1#wechat_redirect";
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            if($scope.user.id==useID){
                $scope.deleteStatus=true;
            }else{
                $scope.deleteStatus=false;
            }
            $scope.selectReplyId=ID;
            $scope.selectReplydetail=detail;
            $scope.showoperationstatus=true;
        }
        $scope.hideoperationdailog=function(){
            $scope.showoperationstatus=false;
        }
        //回复 ui-sref="main.allreply({comment_id:review.id})"
        $scope.operationreply=function(event){
            event.stopPropagation()//阻止冒泡
            $state.go('main.viewallreply',{comment_id:$scope.selectReplyId,commentType:'7'},true);
        }
        //删除
        $scope.operationdelet=function(event){
            event.stopPropagation()//阻止冒泡
            $api.post("app/viewcomment/del", {
                comment_id: $scope.selectReplyId,
                type: ''
            }, true)
                .then(function (ret) {
                    $alert.show("删除成功!");
                    location.reload();

                }, function (err) {
                    $alert.show(err);

                })
        }
        //举报  app/viewcomment/report  type=1
        $scope.operationReport=function(content,event){
            event.stopPropagation()//阻止冒泡
            $api.post("app/viewcomment/report", {
                comment_id: $scope.selectReplyId,
                type: '7',
                content:content
            }, true)
                .then(function (ret) {
                    $alert.show("举报成功!");
                    $scope.operationReportdailogstatus=false;
                }, function (err) {
                    $alert.show(err);

                })
        }
        //举报弹窗
        $scope.showReportdailog=function(event){
            event.stopPropagation()//阻止冒泡
            $scope.operationReportdailogstatus=true;
            $scope.showoperationstatus=false;
        }
        $scope.hideReportdailog=function(){
            $scope.operationReportdailogstatus=false;
        }


    })
